package com.eascs.ticket.ticket.controller;

import java.util.Date;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.eascs.common.assertion.util.AssertInfoUtils;
import com.eascs.common.util.ObjectUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.ticket.common.entity.EntityUtil;
import com.eascs.ticket.configuration.entity.TicketStatusConstant;
import com.eascs.ticket.ticket.entity.Ticket;
import com.eascs.ticket.ticket.form.InsertTicketForm;
import com.eascs.ticket.ticket.service.TicketService;
import com.eascs.web.sso.UserHolder;

@Component
public class InsertTicketComponet {
	@Inject
	private TicketService ticketService;

	public Ticket insertTicket(InsertTicketForm insertTicketForm) {
		checkStartAndEndDate(insertTicketForm.getStartTime(), insertTicketForm.getEndTime());

		Ticket ticket = new Ticket();
		ObjectUtil.copySimpleProperties(insertTicketForm, ticket);
		EntityUtil.initInsertEntity(ticket);
		ticket.setStatus(TicketStatusConstant.TICKET_STATUS_NEW);
		ticket.setOperator(UserHolder.getUser().getCode());
		ticket.setOperatorName(UserHolder.getUser().getCname());

		if (StringUtil.isEmpty(ticket.getReporter()) || StringUtil.isEmpty(ticket.getReporterName())) {
			ticket.setReporter(UserHolder.getUser().getCode());
			ticket.setReporterName(UserHolder.getUser().getCname());
		}

		if (StringUtil.hasText(ticket.getParentTicketId())) {
			ticket.setVersionTicketId(this.ticketService.getTicketById(ticket.getParentTicketId()).getVersionTicketId());
		}

		return ticketService.insertTicket(ticket);
	}

	public void checkStartAndEndDate(Date start, Date end) {
		if (null == start || null == end)
			return;
		AssertInfoUtils.assertTrue(end.getTime() - start.getTime() >= 0, "开始和结束时间设置不合理");
	}

}
